<template>
  <div class="main">
    <el-steps :active="step" finish-status="success" align-center>
      <el-step title="MakeNewSale" />
      <el-step title="EnterItem" />
      <el-step title="EndSale" />
      <el-step title="MakePayment" />
    </el-steps>
    <el-divider />
    <el-row :gutter="20">
      <el-col :span="5">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>商品录入</span>
            </div>
          </template>
          <el-form :model="enterItemForm" label-width="auto">
            <el-form-item label="商品编码">
              <el-select
                v-model="enterItemForm.itemSn"
                placeholder="请选择商品"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.productSn"
                  :label="item.productName"
                  :value="item.productSn"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订购数量">
              <el-input-number
                v-model="enterItemForm.quantity"
                :min="1"
                :max="10"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="small"
                :disabled="step !== 1"
                @click="handleEnterItem"
                >ENTER ITEM</el-button
              >
              <el-button
                type="warning"
                size="small"
                :disabled="step !== 1"
                @click="handleEndSale"
                >END SALE</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
        <el-divider />
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单支付</span>
            </div>
          </template>

          <el-form :model="makePaymentForm" label-width="auto">
            <el-form-item label="付款金额">
              <el-input v-model="makePaymentForm.cashTendered" />
            </el-form-item>
            <el-form-item label="找零">
              <el-input v-model="changeDue" />
            </el-form-item>

            <el-form-item>
              <el-button
                type="danger"
                size="small"
                :disabled="step !== 3"
                @click="handleMakePayment"
                >MAKE PAYMENT</el-button
              >
              <el-button
                type="info"
                size="small"
                :disabled="step !== 3"
                @click="handleHoldOrder"
                >HOLD ORDER</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-descriptions
          class="margin-top"
          title="订单信息"
          :column="3"
          :size="size"
          border
        >
          <template #extra>
            <el-button
              type="success"
              :disabled="!(step === 0 || step === 4)"
              @click="handleMakeNewSale"
              >MAKE NEW SALE</el-button
            >
          </template>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <user-filled />
                </el-icon>
                会员
              </div>
            </template>
            {{ saleInfo.userName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <tickets />
                </el-icon>
                状态
              </div>
            </template>
            <el-tag size="small">{{ saleInfo.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <goods-filled />
                </el-icon>
                订单号
              </div>
            </template>
            {{ saleInfo.saleNo }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <wallet-filled />
                </el-icon>
                总金额
              </div>
            </template>
            {{ saleInfo.totalAmount }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <grid />
                </el-icon>
                总件数
              </div>
            </template>
            {{ saleInfo.totalQuantity }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <info-filled />
                </el-icon>
                备注
              </div>
            </template>
            {{ saleInfo.remark }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单明细</span>
            </div>
          </template>
          <el-table
            :data="tableData"
            style="width: 100%"
            :row-class-name="tableRowClassName"
          >
            <el-table-column prop="index" label="序号" width="100" />
            <el-table-column prop="itemSn" label="商品编码" width="180" />
            <el-table-column prop="productName" label="商品名称" width="180" />
            <el-table-column prop="price" label="销售价格" width="180" />
            <el-table-column prop="quantity" label="订购数量" width="200">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  size="small"
                  :disabled="step !== 1"
                  :min="1"
                  :max="10"
                  @change="handleChangeQuantity(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  size="small"
                  :disabled="step !== 1"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <template #footer
            >总件数: {{ saleInfo.totalQuantity }}件 ｜ 总金额:
            {{ saleInfo.totalAmount }} 元</template
          >
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import type { ComponentSize } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import type { ProductDTO } from "@/api/product";
import { listAllProduct } from "@/api/product";
import type {
  Sale,
  SaleItem,
  EnterItemForm,
  MakePaymentForm
} from "@/api/sale";
import {
  makeNewSale,
  enterItem,
  endSale,
  makePayment,
  changeQuantity,
  deleteSaleItem
} from "@/api/sale";

const productOptions = ref<ProductDTO[]>([]);
/**
 * 下拉框获取产品
 * 如果产品多，可为下拉框添加远程搜索功能实现产品筛选
 */
const getProductOptions = () => {
  listAllProduct().then(response => {
    productOptions.value = response.data;
  });
};

onMounted(() => {
  getProductOptions();
});

// 控制业务步骤
const step = ref(0);

const saleInfo = ref<Sale>({
  userName: "张三",
  saleNo: "",
  totalAmount: 0.0,
  totalQuantity: 0,
  status: "已预订",
  remark: "送货上门"
});

/**
 * 初始化数据
 */
function initData() {
  tableData.value = [];
  enterItemForm.value = {
    itemSn: "",
    quantity: 1
  };
  makePaymentForm.value = {
    cashTendered: 0.0,
    payMethod: "CASH"
  };
  saleInfo.value.totalQuantity = 0;
  step.value = 0;
}

/**
 * 第1步: 开始一次新的销售
 * 仅用于前端测试, 实际项目从后端获取saleInfo
 */
function handleMakeNewSale() {
  initData();
  makeNewSale().then(response => {
    saleInfo.value.saleNo = response.data.saleNo;
    saleInfo.value.totalAmount = response.data.total;
  });
  step.value = 1;
}

const enterItemForm = ref<EnterItemForm>({
  itemSn: "",
  quantity: 1
});

const tableData = ref<SaleItem[]>([]);

/**
 * 第2步: 录入商品明细
 */
function handleEnterItem() {
  enterItem(enterItemForm.value).then(response => {
    tableData.value = response.data;
  });
}

/**
 * 第3步: 结束录入商品明细
 * 计算总金额
 */
function handleEndSale() {
  endSale().then(response => {
    saleInfo.value.totalAmount = response.data.total;
    makePaymentForm.value.cashTendered = saleInfo.value.totalAmount;
  });
  step.value = 3;
}

const makePaymentForm = ref<MakePaymentForm>({
  cashTendered: 0.0,
  payMethod: "CASH"
});

/**
 * 计算属性自动计算找零
 */
const changeDue = computed(() => {
  return makePaymentForm.value.cashTendered - saleInfo.value.totalAmount;
});

/**
 * 第4步: 完成支付
 */
function handleMakePayment() {
  if (makePaymentForm.value.cashTendered < saleInfo.value.totalAmount) {
    ElMessage({ type: "warning", message: "输入的付款金额小于订单总金额" });
  } else {
    makePayment(makePaymentForm.value).then(response => {
      saleInfo.value.status = response.data.status;
      ElMessage({ type: "success", message: response.msg });
    });
    step.value = 4;
  }
}

/**
 * 挂单
 */
function handleHoldOrder() {
  ElMessageBox.confirm("确认挂单操作？", "警告").then(() => {
    step.value = 4;
  });
}
/**
 * 终极任务二: 修改订单明细数量
 */
const handleChangeQuantity = (row: SaleItem) => {
  changeQuantity(row).then(response => {
    ElMessage({ type: "success", message: response.msg });
  });
};
/**
 * 终极任务三: 删除某个订单明细
 * @param row
 */
const handleDelete = (row: SaleItem) => {
  const itemSn = row.itemSn;
  deleteSaleItem(itemSn).then(response => {
    tableData.value = response.data;
    ElMessage({ type: "success", message: response.msg });
  });
};

/**
 * 表格样式
 */
const size = ref<ComponentSize>("default");

const iconStyle = computed(() => {
  const marginMap: any = {
    large: "8px",
    default: "6px",
    small: "4px"
  };
  return {
    marginRight: marginMap[size.value] || marginMap.default
  };
});
const tableRowClassName = ({
  row,
  rowIndex
}: {
  row: SaleItem;
  rowIndex: number;
}) => {
  row.index = rowIndex + 1;
  if (rowIndex % 2 === 0) {
    return "warning-row";
  } else if (rowIndex % 2 === 1) {
    return "success-row";
  }
  return "";
};
</script>

<style>
.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
